/**
 * @Title: index.js
 * @Description: index 学员管理
 * @author: Fanchao
 * @date: 2020/8/1 11:52 下午
 * @version V1.0
 */

import React, { useEffect, useState } from 'react';
import { Table, Button, Popconfirm, Upload, message } from 'antd';
import styles from './index.less';
import SectionTitle from 'components/SectionTitle';
import AddSomeButton from 'components/AddSomeButton';
import FilterByKeyWord from 'components/FilterByKeyWord';
import { connect } from 'umi';
import UserModal from '@/pages/users/students/components/UserModal';
import storageUtils from 'utils/storage';
import UpdatePassword from 'components/UpdatePassword';
import { postDownloadTemplate } from 'api/index';
import * as FileSaver from 'file-saver';
import axios from 'axios';

const Teacher = ({ students: { dataSource, keyword, reqPageInfo, modalTitle, modalVisible }, dispatch, loading }) => {
    const [passwordVisible, setPasswordVisible] = useState(false);
    const [userId, setUserId] = useState(null);
    const isAdmin = storageUtils.getUser().userRoleTypes.includes('Admin');
    useEffect(() => {
        dispatch({
            type: 'students/getDataSource',
            payload: {
                keyword: '',
                reqPageInfo: {
                    pageNumber: 1,
                    pageSize: 10,
                },
            },
        });
        dispatch({
            type: 'students/getUnitsTreeData',
            payload: {},
        });
    }, []);


    const downLoad = async () => {
        const res = await postDownloadTemplate({ importTemplateType: 'student' });
        let blob = new Blob([res.file], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' });
        FileSaver.saveAs(blob, res.filename);
    };
    const columns = [
        {
            title: '学员姓名',
            dataIndex: 'studentRealName',
            align: 'left',
        },
        {
            title: '学员证号',
            dataIndex: 'credentialsNo',
            align: 'left',
        },
        {
            title: '入学时间',
            dataIndex: 'enterSchoolTime',
            align: 'left',
        },
        {
            title: '所在学员队',
            dataIndex: 'department',
            align: 'left',
        },
        isAdmin ? (
            {
                title: '操作',
                align: 'left',
                render: (item) => {
                    return (
                        <div>
                            <Button
                                style={{ padding: 2, fontWeight: 'bold', color: 'gold' }}
                                type="link"
                                onClick={() => updatePassword(item)}
                            >
                                重置密码
                            </Button>
                            <Button style={{ padding: 2, fontWeight: 'bold' }} type="link"
                                    onClick={() => updateItem(item)}>修改</Button>
                            <Popconfirm title="是否要删除？" onConfirm={() => handleDelete(item)}>
                                <Button style={{ padding: 2, color: '#C21217', fontWeight: 'bold' }}
                                        type="link">删除</Button>
                            </Popconfirm>
                        </div>
                    );
                },
            }
        ) : {},

    ];
    const title = '新增学员';

    const addItem = (item) => {
        dispatch({
            type: 'students/setModalTitle',
            payload: '新增学员',
        });
        dispatch({
            type: 'students/setModalVisible',
            payload: true,
        });
        dispatch({
            type: 'students/setItemData',
            payload: item,
        });
        dispatch({
            type: 'students/getTeachClassList',
            payload: {},
        });
        dispatch({
            type: 'students/getTrainingTypeList',
            payload: {},
        });
    };
    const updateItem = (item) => {
        dispatch({
            type: 'students/setModalTitle',
            payload: '修改学员',
        });
        dispatch({
            type: 'students/setModalVisible',
            payload: true,
        });
        dispatch({
            type: 'students/setItemData',
            payload: item,
        });
    };
    const handleDelete = (item) => {
        dispatch({
            type: 'students/removeStudentUser',
            payload: {
                studentUserId: item.studentUserId,
            },
            callback: (result) => {
                if (result) {
                    dispatch({
                        type: 'students/getDataSource',
                        payload: {
                            keyword: '',
                            reqPageInfo: {
                                pageNumber: 1,
                                pageSize: 10,
                            },
                        },
                    });
                }
            },
        });
    };
    const updatePassword = (item) => {
        setPasswordVisible(true);
        setUserId(item.userId);
    };
    const searchByKeyWord = (keyword) => {
        dispatch({
            type: 'students/getDataSource',
            payload: {
                keyword,
                reqPageInfo: {
                    pageNumber: reqPageInfo.pageNumber,
                    pageSize: reqPageInfo.pageSize,
                },
            },
        });
    };
    const searchByPageNumber = (pageNumber) => {
        dispatch({
            type: 'students/getDataSource',
            payload: {
                keyword,
                reqPageInfo: {
                    pageNumber,
                    pageSize: reqPageInfo.pageSize,
                },
            },
        });
    };
    const customRequest = async (option) => {
        const file = option.file;
        const formData = new FormData();
        formData.append('importFile', file);
        let config = {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        };
        axios.post('/file/importStudentUser', formData, config).then((res) => {
            if (res.data.status === 'success') {
                message.success(`导入${res.data.result}成功`);
            } else {
                message.error(res.data.message);
            }

        }).then(res => {

        }).catch(err => {

        });
    };
    return (
        <div className={styles.pageContainer}>
            {
                isAdmin ? (
                    <div className={styles.pageContainerHeader}>
                        <SectionTitle title={title}/>
                        <div className={styles.btnGroup}>

                            <div style={{ width: '220px' }} onClick={() => addItem({})}>
                                <AddSomeButton title={title}/>
                            </div>
                            <div onClick={downLoad} style={{ width: '220px', margin: '0 16px' }}>
                                <AddSomeButton title={'下载模板'}/>
                            </div>
                            <Upload
                                style={{ width: '220px' }}
                                fileList={[]}
                                customRequest={customRequest}
                            >
                                <AddSomeButton title={'导入学员'}/>
                            </Upload>
                        </div>
                    </div>
                ) : null
            }

            <div className={styles.pageContainerTable}>
                <SectionTitle title={'已有学员'}/>
                <FilterByKeyWord onSearch={keyword => searchByKeyWord(keyword)}
                                 onReset={keyword => searchByKeyWord(keyword)}/>
                <div className={styles.tableContainer}>
                    <Table
                        bordered={false} // 是否有边框
                        rowKey='studentUserId' // 唯一key值
                        loading={loading} // 加载动画
                        columns={columns} // 表头
                        dataSource={dataSource.contentList}
                        pagination={{
                            total: dataSource.totalElements,// 总记录数
                            defaultPageSize: 10, // 默认显示条数
                            showQuickJumper: true, // 快速跳转
                            showSizeChanger: true, // 一页展示数据条数
                            onChange: (pageNumber) => searchByPageNumber(pageNumber),
                            showTotal: () => {
                                return `共${dataSource.totalElements}条`;
                            },
                        }}
                    />
                </div>
            </div>
            <UserModal
                title={modalTitle}
                visible={modalVisible}
            />
            <UpdatePassword
                visible={passwordVisible}
                userId={userId}
                cb={(value) => setPasswordVisible(value)}
            />
        </div>
    );
};
export default connect(({ students, dispatch, loading }) => ({
    students,
    dispatch,
    loading: loading.effects['students/getDataSource'],
}))(Teacher);
